/**
 * @file 添加订单-百度地图
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/12/03 11:05:40
 */

layui.define(['layer', '$http', 'zmnUtils'], function (exports) {
    var $ = layui.$;
    var layer = layui.layer;
    var $http = layui.$http;
    var zmnUtils = layui.zmnUtils;
    var defaultCommunityId = 999999;
    var defaultStreetSource = 2;

    var ACTIVE_CLASS = 'layui-btn-primary';
    var STROKE_COLOR = "#ff0000";

    // 获取小区地址信息
    var COMMUNITY_ADDRESS_URL = '/area/queryCommunity.action';
    // 百度地图地址联想
    var BAIDU_MAP_SUGGESTED = "//api.map.baidu.com/place/v2/suggestion";

    var MAP_DATA_TYPE = {

    };

        /**
     * 获取多边形
     * @param points 点集
     * @returns {o.Polygon|t|r.Polygon|Polygon}
     */
    function getPolygon(points) {
        return new BMap.Polygon(points, {
            strokeColor: STROKE_COLOR,
            strokeWeight: 2,
            strokeOpacity: 0.5,
            enableClicking: false,
            enableMassClear: true
        });
    }

    /**
     * 获取圆形
     * @param points 点集
     * @returns {o.Polygon|t|r.Polygon|Polygon}
     */
    function getCircle(center, radius) {
        return new BMap.Circle(center, radius, {
            strokeColor: STROKE_COLOR,
            strokeWeight: 2,
            strokeOpacity: 0.5,
            enableClicking: false,
            enableMassClear: true
        });
    }

    function MapCacha(map) {
        this._map = map;
        this._list = [];
        this._pointArray = [];

        this.add = function (item) {
            var self = this;
            var data = self._list;
            if (zmnUtils.isArray(data)) {
                this._list.push(item);
            }

            this.render();
        }

        this.clear = function () {
            this.render(true);
            this._list = [];
            this._pointArray = [];
        }
    }

    function PolygonsCacha (map) {
        MapCacha.call(this, map);
    }

    PolygonsCacha.prototype.render = function (remove) {
        var self = this;
        var data = this._list;

        if (!zmnUtils.isArray(data)) {
            return;
        }

        data.forEach(function (polygons) {
            polygons.forEach(function (ply) {
                if (remove) {
                    self._map.removeOverlay(ply);
                } else {
                    self._map.addOverlay(ply);
                    self._pointArray = self._pointArray.concat(ply.getPath());
                }
            });
        });

        if (!remove && self._pointArray.length) {
            self._map.setViewport(self._pointArray);
        }
    }


    function MarkersCacha(map) {
        MapCacha.call(this, map)
    }

    MarkersCacha.prototype.render = function (remove) {
        var self = this;
        var data = this._list;

        if (!zmnUtils.isArray(data)) {
            return;
        }

        data.forEach(function (item) {
            if (remove) {
                self._map.removeOverlay(item);
            } else {
                self._map.addOverlay(item);
            }
        });
    }

    var saddressmap = {
        // 地图实例
        _map: null,
        _polygons: null,
        _markers: null,
        // 窗口 index
        _layerIndex: parent.layer.getFrameIndex(window.name),
        // 传入参数值
        _saddressOptions: {},
        // 当前选中坐标
        _selectedPoint: null,
        // 逆地址解析
        _geoc: new BMap.Geocoder(),
        // 选中地址
        _selectedAddress: {},

        // 街道id
        communityId: defaultCommunityId,
        streetSource: defaultStreetSource,
        district:'',

        /**
         * 初始化地图
         */
        init: function (options) {
            var self = this;

            self._saddressOptions = options;

            // 初始化地图
            var mapInstance = new BMap.Map("allmap", {
                enableMapClick: false
            });

            self._map = mapInstance;
            self._polygons = new PolygonsCacha(mapInstance);
            self._markers = new MarkersCacha(mapInstance);

            self._map.enableScrollWheelZoom();
            self._map.addControl(new BMap.NavigationControl());

            var location = self._saddressOptions.location;
            // 检查是否带过来经纬度
            if (location && location.lng && location.lat) {
                self.district = self._saddressOptions.countyName;
                self.communityId = self._saddressOptions.streetId;
                self.streetSource = self._saddressOptions.streetSource;

                self._selectedPoint = new BMap.Point(location.lng, location.lat);
                self._map.centerAndZoom(self._selectedPoint, 18);
                // 创建 marker
                self._createSelectedMarker();
                // 创建信息框
                self._getLoaction(self._selectedPoint, self._saddressOptions.street);
                // 联想
                self._suggest(self._selectedPoint);
            } else {
                var cityName = self._saddressOptions.cityName.replace("辖区", "").replace("辖县", "");
                self._geoc.getPoint(cityName, function (res) {
                    self._map.centerAndZoom(res, 11);
                }, cityName);
            }
            
            // 添加服务范围
            if (!self._saddressOptions.src) {
                self._initServiceScope(self._saddressOptions.cityId,self._saddressOptions.productShowType,self._saddressOptions.productId, self._saddressOptions.plat);
            }

            self.initEvent();
        },

        /**
         * 初始化地图相关事件
         */
        initEvent: function () {
            var self = this;

            // 为地图添加点击事件
            self._map.addEventListener("click", self._mapClick());

            // 设置 infoWindow 的点击事件处理函数
            window.handleBtnClick = function () {
                self.confirmAddress();
            };

            // 联想输入框输入事件
            var timer;
            $('#searchText').on('input', function () {
                var inputEle = this;
                clearTimeout(timer);
                timer = setTimeout(function () {
                    self.suggestAddress(inputEle);
                }, 300);
            });

            // 地址联想点击事件
            $('#peripheryPanel').on('click', 'li', function () {
                var $li = $(this);
                $($li).addClass("selected").siblings().removeClass("selected");
                self._selectedPoint = new BMap.Point($li.data('lng'), $li.data('lat'));

                self._createSelectedMarker();
                self._getLoaction(self._selectedPoint, $(this).data('name'));

                // 赋值 来源&小区地址
                self.communityId = $li.data('communityid');
                self.streetSource = $li.data('source');
                self.district = $li.data('district');

                self._map.centerAndZoom(self._selectedPoint, 17);
            });
        },

        /**
         * 保存选中的合法地址
         */
        confirmAddress: function () {
            var self = this;

            // self._saddressOptions.callBack(self._selectedAddress);

            self._isPinitInServiceScope(self._selectedAddress.point);

        },

        _closeDialog: function () {
            var self = this;
            // 关闭窗口
            parent.layer.close(self._layerIndex);
        },

        /**
         * 生成地图点击事件处理函数
         * @returns {Function} 地图点击事件处理函数
         * @private
         */
        _mapClick: function () {
            var self = this;
            return function (res) {
                self._selectedPoint = res.point;
                self._createSelectedMarker();
                self._getLoaction(self._selectedPoint);
                self._suggest(self._selectedPoint);
            }
        },

        /**
         * 生成服务服务范围覆盖层
         * @param cityId
         * @param serviceItemId
         * @param channelId
         * @private
         */
        // 初始化服务范围
        // TODO
		_initServiceScope: function (cityId, productShowType, productId, plat) {
            var self = this;
            $http.get('/area/point/list', {
                plat: plat,
                cityId: cityId,
                productId: productId,
				productShowType: productShowType,
			}).then(function (cityList) {
                if (zmnUtils.isArray(cityList) && cityList.length) {
                    var $container = $('<div></div>');
                    cityList.forEach(function(city, index) {
                        var classStr = 'layui-btn';
                        if (index !== 0) {
                            classStr += ' ' + ACTIVE_CLASS;
                        }

                        var $btn = $(
                            `<button type="button" class="${ classStr }">${ city.companyName }地图</button>`
                        );

                        $container.append(
                            $btn.on('click', function () {
                                var $this = $(this);

                                self._renderServiceScope(city.pointList);
                                $this.removeClass(ACTIVE_CLASS)
                                    .siblings()
                                    .addClass(ACTIVE_CLASS);
                            })
                        );

                        index === 0
                            ? self._renderServiceScope(city.pointList)
                            : void(0);
                    });

                    $('#city-list').append($container);
                }
            })

        },

        _renderServiceScope: function (pointList) {
            var self = this;
            var polygonsCache = self._polygons;
            self._createPolygonList(pointList).then(function (data) {
                polygonsCache.clear();
                polygonsCache.add(data);
            });
        },

        _createPolygonList: function (pointList) {
            var self = this;
            var def = $.Deferred();

            if (
                !zmnUtils.isArray(pointList) ||
                !pointList.length
            ) {
                return [];
            }

            var overlayList = [];
            var flag = pointList.length;

            function getOverlayList () {
                return overlayList.filter(function(item) {
                    return !!item;
                });
            }

            function checkOverlayState () {
                if (overlayList.length >= flag) {
                    def.resolve(getOverlayList());
                }
            }

            pointList.forEach(function (item) {
                var data = item.mapData || '[]';
                var jsonArr = eval('(' + data + ')');

                var overlay = null;

                switch (item.mapDataType) {
                    case 1: {
                        overlay = getPolygon(jsonArr);
                        overlayList.push(overlay);
                        checkOverlayState();
                        break;
                    }

                    case 2: {
                        if (item.longitude && item.latitude && item.mapData) {
                            var point = new BMap.Point(item.longitude, item.latitude);
                            overlay = getCircle(point, item.mapData)
                            overlayList.push(overlay);
                        }

                        checkOverlayState();
                        break;
                    }

                    case 3: {
                        var boundary = new BMap.Boundary();
                        var city = item.city || '';
                        var county = item.county || '';

                        var cityName = city.replace('辖区', '')
                            .replace('辖县', '');
                        var regionName = cityName + county;

                        boundary.get(regionName, function (response) {
                            if (
                                zmnUtils.isObject(response) &&
                                zmnUtils.isArray(response.boundaries)) {
                                response.boundaries.forEach(function (item) {
                                    var overlay = getPolygon(item);
                                    overlayList.push(overlay);
                                });
                            }

                            checkOverlayState();
                        });

                        break;
                    }

                    default:
                        break;
                }
            })

            return def.promise();
        },

        _isPinitInServiceScope: function (location) {
            var self = this;
            self._saddressOptions.verifyFunc(self._selectedAddress, function (data) {
                self._saddressOptions.callBack(data, self._selectedAddress);
                self._closeDialog();
            }, function (msg) {
                layer.msg(msg);
            });
        },

        /**
         * 创建选中 marker
         * @private
         */
        _createSelectedMarker: function () {
            var self = this;
            var point = self._selectedPoint;
            var markersCache = self._markers;
            if (point) {
                // 清除地图覆盖物
                markersCache.clear();
                // 创建marker
                var mkr = new BMap.Marker(point, {
                    enableDragging: true
                });

                // 设置拖拽监听
                mkr.addEventListener("dragend", self._mkrDragend);

                // 往地图添加marker
                markersCache.add(mkr);
            }
        },

        /**
         * marker 移动事件处理函数
         * @param {Object} res 移动事件回调
         * @private
         */
        _mkrDragend: function(res) {
            var self = saddressmap;
            self._selectedPoint = res.point;

            self._getLoaction(res.point);
            self._suggest(res.point);
        },

        /**
         * 经纬度转地址
         * @param {Object} point 地图点
         * @param {string} street 地址
         * @private
         */
        _getLoaction: function(point, street) {
            var self = this;

            var point = new BMap.Point(point.lng, point.lat);

            //获取地址
            self._geoc.getLocation(point, function(res) {
                self._selectedAddress = res;
                var addComp = res.addressComponents;
                if (street) {
                    self._selectedAddress.address = street;
                    self._selectedAddress.communityId = self.communityId;
                    self._selectedAddress.streetSource = self.streetSource;
                    self._selectedAddress.addressComponents.street = street;
                    self._selectedAddress.addressComponents.district = self.district;
                } else if (res.surroundingPois && res.surroundingPois.length > 0) {
                    var poi0 = res.surroundingPois[0];
                    self._selectedAddress.point = poi0.point;
                    self._selectedAddress.address = poi0.title;
                    self._selectedAddress.communityId = defaultCommunityId;
                    self._selectedAddress.streetSource = defaultStreetSource;
                    self._selectedAddress.addressComponents.district = '';
                    self._selectedAddress.addressComponents.street = poi0.title;
                } else {
                    self._selectedAddress.address = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber;
                    self._selectedAddress.communityId = defaultCommunityId;
                    self._selectedAddress.streetSource = defaultStreetSource;
                    self._selectedAddress.addressComponents.district = addComp.district;
                    self._selectedAddress.addressComponents.street = addComp.street;
                }
                self._createInfoWindow();
            });
        },

        /**
         * 创建信息面板
         * @private
         */
        _createInfoWindow: function () {
            var self = this;
            var htmlInfo = self._selectedAddress.address + "<button class='btn btn-green' onclick='handleBtnClick()'>确认</button>";
            var infoWindow = new BMap.InfoWindow(htmlInfo, {
                width: 340,
                height: 50
            });

            self._map.openInfoWindow(infoWindow, self._selectedPoint);
        },

        /**
         * 地址联想输入框输入处理
         * @param {object} elem 输入框 dom 对象
         */
        suggestAddress: function(elem) {
            var addr = $(elem).val();
            saddressmap._suggest(null, addr);
        },

        /**
         * 地址联想
         * @param {Object} point 地图点
         * @param address 地址
         * @private
         */
        _suggest: function(point, address) {
            var self = this;
            //清空
            $("#peripheryPanel").empty();
            if (point) {
                self._initPeripheryByPoint(point);
            } else if (address) {
                self._initPeripheryByAddress(address);
            }

            this.communityId = defaultCommunityId;
            this.streetSource = defaultStreetSource;
        },

        /**
         * 根据查询文本查询相关地址信息
         * @param {string} queryText 查询文本
         */
        _initPeripheryByAddress: function (queryText) {
            var self = this;
            var cityName = self._saddressOptions.cityName.replace("辖区", "").replace("辖县", "");
            var cityId = self._saddressOptions.cityId;

            self._fetchSuggestedStreet({
                queryStr: queryText,
                cityName: cityName,
                cityId: cityId,
                ak: addOrderWebAk
            }, self._calPreiphery);
        },

        /**
         * 获取小区库的地址
         * @param params 查询参数
         * @param cb 回调函数
         */
        _fetchSuggestedStreet: function (params, cb) {
            var self = this;
            self._fetchBaiduSuggestedStreet(params, cb);
            // $.ajax({
            //     type: "get",
            //     url: COMMUNITY_ADDRESS_URL,
            //     data: params,
            //     success: function (resultData) {
            //         if (resultData.statusBool) {
            //             if (resultData.data === undefined) {
            //                 resultData.data = [];
            //             }
            //             var data = resultData.data;
            //             // 过滤搜索结果
            //             data = data.filter((item) => {
            //                 if(!item.location){
            //                     return false;
            //                 }
            //                 return !item.city || item.city.indexOf(params.cityName.slice(0, 1)) !== -1;
            //             });
            //             cb(data);
            //         } else {
            //             console.log(params, resultData.message);
            //             // 异常，调用百度地址
            //             self._fetchBaiduSuggestedStreet(params, cb);
            //         }
            //     },
            //     error: function () {
            //         // 异常，调用百度地址
            //         self._fetchBaiduSuggestedStreet(params, cb);
            //     },
            // });
        },

        /**
         * 获取百度联想出的地址
         * @param params 查询参数
         * @param cb 回调函数
         */
        _fetchBaiduSuggestedStreet: function (params, cb) {
            $.ajax({
                url: BAIDU_MAP_SUGGESTED,
                type: "GET",
                dataType: "jsonp",
                data: {
                    query: params.queryStr,
                    region: params.cityName,
                    city_limit: true,
                    output: "json",
                    ak: params.ak,
                },
                success: function (response) {
                    if (response.status === 0) {
                        // 过滤搜索结果
                        var data = response.result.filter((item) => {
                            if ( item.name == item.province || item.name == item.city || item.name == item.district || item.name.endsWith('-道路') || item.name.endsWith('镇') || item.name.endsWith('乡')) {
                                return false;
                            }
                            return (item.city.indexOf(params.cityName.slice(0, 1)) !== -1 ) || (!item.city && item.district.indexOf(params.cityName.slice(0, 1)) !== -1);
                        });
                        cb(data);
                    }
                },
            });
        },

        /**
         * 根据地图点查询相关地址信息
         * @param {object} point 经纬度点
         */
        _initPeripheryByPoint: function (point) {
            var self = this;
            var ulr = "//api.map.baidu.com/place/v2/search?q=店$厦$街$区$家$楼$校$司$园&scope=1&output=json&page_size=30&location=" + point.lat + "," + point.lng + "&radius=100&filter=sort_name:distance|sort_rule:1&ak="+ addOrderWebAk +"&callback=?";
            $.getJSON(ulr, null, function (res) {
                if (res.status == 0) {
                    self._calPreiphery(res.results);
                }
            });
        },

        /**
         * 渲染地址联想列表
         * @param {array} data 地址数据
         * @private
         */
        _calPreiphery: function (data) {
            var self = this;
            var $ul = $("#peripheryPanel");
            $.each(data, function (ind, val) {
                if (val.location && val.location.lat && val.name &&
                    val.name != val.province && val.name != val.city && val.name != val.district) {
                    let address = val.city ? val.city + (val.district || '') : (val.address || '');
                    let communityId = '';
                    let streetSource = '';
                    if (val.communityId) {
                        communityId = val.communityId;
                    }else {
                        communityId = defaultCommunityId;
                    }
                    if (val.source) {
                        streetSource = val.source;
                    }else {
                        streetSource = defaultStreetSource;
                    }
                    var $li = $("<li data-lat='" + val.location.lat + "' data-lng='" + val.location.lng + "' data-communityid='" + communityId + "' data-source='" + streetSource + "' data-name='" + val.name + "'  data-district='" + (val.district || '') + "'>" + val.name + " <span>" + address + "</span></li>");

                    $ul.append($li);
                }
            });
        }
    };
    /**
     * 初始化页面
     */
    function initPage () {
        saddressmap.init(parent.addressOptions || {});
    }

    /**
     * 初始化页面事件
     */
    function initEvent () {
        // 地图关闭按钮点击事件
        $("#closeMap").click(function () {
            parent.layer.close(saddressmap._layerIndex);
        });
    }

    /**
     * 程序入口
     */
    function init () {
        initPage();
        initEvent();
    }

    init();
    exports('oms_map_address');
});




